package com.elinkway.infinitemovies.ui.activity.play;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.UMengReport;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.httpd.M3u8Httpd;
import com.elinkway.infinitemovies.ui.activity.BaseActivity;
import com.elinkway.infinitemovies.ui.activity.play.VideoPlayerScreenListener.ScreenStateListener;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.TrafficStatsUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.HashMap;

/**
 * 影视大全自有播放器页面
 *
 * @author zhangshuo
 */
@SuppressLint("NewApi")
public class PlayActivitySelfOwn extends BaseActivity implements OnClickListener {

    private ImageView mPlayBack;

    public RelativeLayout mPlayControllView;

    public FrameLayout mVideoplayerParentLayout;

    private final static String TAG = "PlayActivitySelfOwn";

    private final static int LANDSCAPE = 1;

    private final static int LANDSCAPE_REVERSE = 2;

    private final static int SCREEN_ROTATION_ON = 1;

    private static final int LANDSCAPE_MIN_DEGREE = 20;

    private static final int LANDSCAPE_MAX_DEGREE = 160;

    private static final int LANDSCAPE_REVERSE_MIN_DEGREE = 200;

    private static final int LANDSCAPE_REVERSE_MAX_DEGREE = 340;

    private PlayMediaController mPlayMediaController;

    private int mSysAPILevel = 0;

    /**
     * 用户是否选择了在3G网络下播放
     */
    private boolean mIsWifiTo3GFlag;

    /**
     * 播放需要用到的相关数据
     */
    private PlayData mPlayData;

    private NetworkCheckReceiver mCheckReceiver;

    private HandlerInterface mHandlerCallback;

    // wuxinrong modified begin
    // 已经是单例模式了，还创建你妹的对象
    //private DialogUtil dialogUtil;
    // wuxinrong modified end

    private VideoPlayerScreenListener mSceenListener;

    private OrientationEventListener mOrientationListener; // 屏幕方向改变监听器

    private Window mWindow;

    public Boolean fromBackground = false;//从后台切换回来，解决暂停时，从后台切换回来播放从头开始的bug

    private boolean isClickBack = false;

    private static M3u8Httpd m3u8Httpd = new M3u8Httpd(8084);

    private long mLandScapeTime;

    private long mReverseLandScapeTime;

    private Handler mHandler;

    private long mCurrentTime;

    private boolean mIsHalfScreen;
    private int mNavigationBarColor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videoplayer);
        MoviesConstant.isRefreshMyFragment = true;
        MoviesApplication.getInstance().setTopActivity(this);
        initView();
        initData();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mNavigationBarColor = getWindow().getNavigationBarColor();
        }
    }

    private void initView() {
        mWindow = getWindow();
        // 设置当前屏幕不锁屏
        mWindow.setFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mPlayControllView = (RelativeLayout) findViewById(R.id.playcontroll);
        mPlayBack = (ImageView) findViewById(R.id.videoplayer_playback_btn);
        mPlayBack.setVisibility(View.VISIBLE);
        mVideoplayerParentLayout = (FrameLayout) findViewById(R.id.videoplayer_parent_layout);
        mPlayBack.setOnClickListener(this);
    }

    private void initData() {
        mSysAPILevel = Utils.getAPILevel();
        initTrafficStats(mSysAPILevel);

        Intent intent = getIntent();
        if (null != intent) {
            setWifiTo3GFlag(intent.getBooleanExtra(Utils.PLAY_3G_NET, false));
            mIsHalfScreen = intent.getBooleanExtra("mIsHalfScreen", false);
        }

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch(msg.what) {
                    case LANDSCAPE:
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        break;
                    case LANDSCAPE_REVERSE:
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                        break;
                }
                super.handleMessage(msg);
            }
        };

        mOrientationListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int rotation) {
                // 设置横屏
                if (Settings.System.getInt(getContentResolver(),
                        Settings.System.ACCELEROMETER_ROTATION, 0) == SCREEN_ROTATION_ON &&
                        findViewById(R.id.videoplayer_lockscreen) != null &&
                        !(findViewById(R.id.videoplayer_lockscreen)).isSelected()) {
                    if ((rotation >= LANDSCAPE_MIN_DEGREE) && (rotation <= LANDSCAPE_MAX_DEGREE)) {
                        mHandler.removeMessages(LANDSCAPE);
                        mHandler.sendEmptyMessageDelayed(LANDSCAPE_REVERSE, 500);
                    } else if ((rotation > LANDSCAPE_REVERSE_MIN_DEGREE) && (rotation < LANDSCAPE_REVERSE_MAX_DEGREE)) {
                        mHandler.removeMessages(LANDSCAPE_REVERSE);
                        mHandler.sendEmptyMessageDelayed(LANDSCAPE, 500);
                    }
                }
            }
        };
        mOrientationListener.enable();

        // 创建屏幕监听且
        mSceenListener = new VideoPlayerScreenListener(this);
        // 注册屏幕监听广播 并实现屏幕状态监听
        mSceenListener.begin(new PlayerScreenSateListener());

        // wuxinrong modified begin
        //dialogUtil = new DialogUtil(PlayActivitySelfOwn.this);
        // wuxinrong modified end
        mHandlerCallback = new HandlerInterfaceImpl();
        registerCheckNetwork();
        mPlayMediaController = new PlayMediaController(this, mVideoplayerParentLayout);
        // mControlBody.setOnTouchListener(new MyOnTouchListener());

        if (null != intent
                && null != intent.getSerializableExtra(Utils.PLAY_DATA)) {
            mPlayData = (PlayData) intent.getSerializableExtra(Utils.PLAY_DATA);

            //将播放数据提供给播放控制台使用
            mPlayMediaController.setmPlayData(mPlayData, true, false);
            setFullScreen(!mIsHalfScreen);
            if (mIsHalfScreen) {
                BigDataApi.bigDataPageShowReport("Halfscreenplaypage_" + mPlayData.getAid(), new HashMap<String, String>(), this);
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put(BigDataApi.REF, MoviesApplication.getInstance().getLastPageClassName());
                BigDataApi.bigDataPageShowReport("Halfscreenplaypage", hashMap, this);
            }
        }
    }

    /**
     * 初始化网速
     *
     * @param sdkVersion zhangshuo
     *                   2014年8月19日 下午2:06:31
     */
    private void initTrafficStats(int sdkVersion) {
        if (sdkVersion >= 8) {
            TrafficStatsUtil.getPreRxByte();
        }
    }

    @Override
    protected void onStart() {
        try {
            if (!m3u8Httpd.isAlive()) {
                m3u8Httpd.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onStart();
    }

    @Override
    protected void onStop() {
        m3u8Httpd.stop();
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e(TAG, "@@@@@@@@@@@@@@@@@@@@@");
        mCurrentTime = System.currentTimeMillis();
        MobclickAgent.onResume(this);
        if (!Utils.getScreenLockStatus() && null != mPlayMediaController) {
            mPlayMediaController.onResume();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        fromBackground = true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        LogUtils.e(TAG, "!!!!!!!!!!!!!!!onPause");
        super.onPause();
        UmengEventPoster.postWatchTime(mPlayData.getmViewName(), MoviesApplication.getInstance().getLastPageClassName(),
                mPlayData.getCategoryName(), (int)(System.currentTimeMillis() - mCurrentTime) / 1000);
        MobclickAgent.onPause(this);
        PlayerUtils.sendNotPlayingBroadcast(PlayActivitySelfOwn.this);
        // 停止播放器页面刷新
        if (null != mPlayMediaController) {
            mPlayMediaController.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e(TAG, "!!!!!player!!!!!onDestroy!!!!!!!");
        mSceenListener.unregisterListener();
        setWifiTo3GFlag(false);
        unregisterCheckNetwork();
        fromBackground = false;
        mOrientationListener.disable();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && 0 == event.getRepeatCount()) {
            isClickBack = true;
            return true;
        }
        return false;
    }

    /**
     * 监听手机网络变化
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * 取消注册检查网络变化*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }

    /**
     * 检测当前网络状态
     */
    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (!mPlayData.getIsLocalVideo() && !getWifiTo3GFlag())
                    checkNetwork(intent);
            }
        }
    }

    protected void checkNetwork(Intent intent) {
        if (mHandlerCallback != null) {

            //读取保存的之前网络状态
            SharedPreferences priorNetState = getSharedPreferences("priornetstate",
                    Activity.MODE_PRIVATE);

            int priorNetType = priorNetState.getInt("netstate", 2);

            // wuxinrong modified begin
            DialogUtil instance = DialogUtil.getInstance(PlayActivitySelfOwn.this);
            int nowNetType = mHandlerCallback.checkNetwork(this, intent, mPlayMediaController, instance, priorNetType);
            //int nowNetType = mHandlerCallback.checkNetwork(this, intent, mPlayMediaController, instance, priorNetType);
            // wuxinrong modified end

            SharedPreferences.Editor editor = priorNetState.edit();

            editor.putInt("netstate", nowNetType);
            editor.commit();
        }
    }

    /**
     * 动态展现状态栏 使用这种方式能够使系统状态栏浮在最顶层显示而不占用Activity空间
     *
     * @param enable zhangshuo
     *               2014年5月5日 上午10:54:02
     */
    public void statusBarShow(boolean enable) {
        Window window = getWindow();
        if (enable) {
            WindowManager.LayoutParams attr = window.getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            window.setAttributes(attr);
//            window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            window.setAttributes(lp);
//            window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }


    /**
     * 进行播放劫流上报
     * zhangshuo
     * 2014年5月5日 下午5:44:15
     */
    private void reportUMengPlayer() {
        UMengReport uMengReport = mPlayMediaController.getmUMengReport();
        if (!uMengReport.ismIsReported()) {
            uMengReport.setEndLoadingTime(System.currentTimeMillis());
            String playResult = uMengReport.getIsMoreThan30() ? UmengEventPoster.PLAYER_RESULT_30_MORE_CANCEL
                    : UmengEventPoster.PLAYER_RESULT_30_CANCEL;
            uMengReport.setPlayresult(playResult);
            uMengReport.setmIsReported(true);
            UmengEventPoster.postPlayer(uMengReport);
        }
    }


    /**
     * 屏幕状态监听实现类
     *
     * @author zhangshuo
     */
    public class PlayerScreenSateListener implements ScreenStateListener {

        @Override
        public void onScreenOn() {

        }

        @Override
        public void onScreenOff() {

        }

        @Override
        public void onUserPresent() {
            if (!Utils.getScreenLockStatus() && null != mPlayMediaController) {
                PlayerUtils.sendPlayingBroadcast(PlayActivitySelfOwn.this);
//				mPlayMediaController.onResume();
            }
        }

    }


    public int getmSysAPILevel() {
        return mSysAPILevel;
    }

    public Window getmWindow() {
        return mWindow;
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && isClickBack) {
            if(mIsHalfScreen){
                if(UIs.isScreenOriatationPortrait(this)){
                    exitPlay();
                }else{
                    setFullScreen(false);
                }
            }else{
                exitPlay();
            }
            isClickBack = false;
        }
        return super.dispatchKeyEvent(event);
    }


    public void setWifiTo3GFlag(boolean flag) {
        mIsWifiTo3GFlag = flag;
    }


    public boolean getWifiTo3GFlag() {
        return mIsWifiTo3GFlag;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.videoplayer_playback_btn:
                if(mIsHalfScreen){
                    if(UIs.isScreenOriatationPortrait(this)){
                        exitPlay();
                    }else{
                        setFullScreen(false);
                    }
                }else{
                    exitPlay();
                }
                break;
            default:
                break;
        }
    }

    public PlayMediaController getPlayMediaController() {
        return mPlayMediaController;
    }

    public void setFullScreen(boolean isFull) {
        if (mPlayControllView == null) {
            return;
        }
        if (isFull) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mVideoplayerParentLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
            mPlayMediaController.setHalfScreenView(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(getResources().getColor(R.color.black));
            }
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            int height = (Utils.getWidthPixels(this)*Utils.getWidthPixels(this))/Utils.getHeightPixels(this);
            mVideoplayerParentLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height));
            mPlayMediaController.setHalfScreenView(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(mNavigationBarColor);
            }
        }
    }

    private void exitPlay(){
        if (null != mPlayMediaController) {
            LinearLayout selectLayout = mPlayMediaController.getmSelectLinearLayout();
            if (null != selectLayout && selectLayout.isShown()) {
                mPlayMediaController.selectUiChange();
            } else {
                mPlayMediaController.playerPause();
                mPlayMediaController.onUserFinish();
                mPlayMediaController.resetPlayData();
                mPlayMediaController.releaseData();
            }
        }
        reportUMengPlayer();
        finish();
    }

}
